package com.jmz.apt.api.service;

import com.jmz.apt.api.dao.MenuDao;
import com.jmz.apt.api.dto.impl.AdminResourceDto;
import com.jmz.apt.api.enums.ResourceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description : {   }
 * @Author : create by NanFeng on 2019-11-06 12:17
 */
@Service
public class MenuService {

    @Autowired
    private MenuDao menuDao;

    public List<AdminResourceDto> encapsulationMenus(List<AdminResourceDto> menus) {
        return getTree(menus);
    }

    private List<AdminResourceDto> getTree(List<AdminResourceDto> menus) {
        List<AdminResourceDto> resources = new ArrayList();
        for (AdminResourceDto vo : menus) {
            if (ResourceCode.RESOURCEPARENTID.getValue() == vo.getParentId()) {
                resources.add(vo);
            }
        }
        //父级菜单存在
        for (AdminResourceDto resource : resources) {
            resource.setChildren(getChildResource(resource.getId(), menus));
        }
        return resources;
    }

    private List<AdminResourceDto>  getChildResource(Integer pid, List<AdminResourceDto> menus) {
        List<AdminResourceDto> childResources = new ArrayList<>();
        for (AdminResourceDto vo : menus) {
            if (vo.getParentId() != null && vo.getParentId().equals(pid)) {
                childResources.add(vo);
            }
        }
        //将子菜单再循环一遍
        for (AdminResourceDto resource : childResources) {
            //递归调用
            resource.setChildren(getChildResource(resource.getId(), menus));
        }
        return childResources;
    }

    public List<AdminResourceDto> getList() {
        return menuDao.getList();
    }
}
